package com.boy.tool.utils;

import cn.hutool.core.util.StrUtil;
import com.boy.commonutils.handler.WhdException;
import com.boy.tool.annotate.Assignment;
import com.boy.tool.enumClass.ExceptionCode;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author whd
 * @date 2024/06/17 11:44:43
 */
public class ClassUtil<A, B> {

    public B partnerToChild(A partner, B child) {
        Class<?> partnerClass = partner.getClass();
        Class<?> childClass = child.getClass().getSuperclass();
        //获取到所有的属性
        Field[] partnerFields = partnerClass.getDeclaredFields();
        for (Field partnerField : partnerFields) {
            partnerField.setAccessible(true);
            Assignment annotation = partnerField.getAnnotation(Assignment.class);
            if (annotation != null) {
                try {
                    String name = partnerField.getName();
                    if (name.isEmpty())throw new WhdException(ExceptionCode.SYSTEM_RUN_EXCEPTION,"获取不到属性名称");
                    String s = Character.toUpperCase(name.charAt(0)) + name.substring(1);
                    String setMethodName = StrUtil.format("set{}", s);
                    String getMethodName = StrUtil.format("get{}", s);
                    Method setMethod = childClass.getMethod(setMethodName, partnerField.getType());
                    Method getMethod = partnerClass.getMethod(getMethodName);
                    setMethod.invoke(child, getMethod.invoke(partner));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return child;
    }
}
